
package com.rt.appauthorize;
import com.rt.schedulenew.utils.coder.DefaultSecurityCoderUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
public class AppAuthInterceptor implements HandlerInterceptor {
    private static Logger log;
    private static String AUTH_FILE_CONTENT;
    private static String MACHINE_CODE;
    @Autowired
    AppAuthProperties appAuthProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
        /*
        String scheme = request.getHeader("X-Forwarded-Proto");
        if (scheme == null || "".equals(scheme)) {
            scheme = request.getScheme();
        }
        String authUrl = scheme + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/rtAuth/index";
        String ajaxHeader = request.getHeader("X-Requested-With");
        String contentType = request.getHeader("Content-Type");
        if (AppAuthInterceptor.MACHINE_CODE == null || "".equals(AppAuthInterceptor.MACHINE_CODE)) {
            AppAuthInterceptor.MACHINE_CODE = AppAuthSerialNumberUtil.getMachineCodeSimple();
        }
        if (AppAuthInterceptor.AUTH_FILE_CONTENT != null && !"".equals(AppAuthInterceptor.AUTH_FILE_CONTENT)) {
            String[] tempStr = AppAuthInterceptor.AUTH_FILE_CONTENT.split(";");
            Long cacheTime = Long.valueOf(tempStr[3]);
            long expire = AppAuthConstants.EXPIRE_TIME + cacheTime;
            if (expire > System.currentTimeMillis()) {
                return true;
            }
        }
        String authFileDir = this.appAuthProperties.getFiledir();
        if (authFileDir == null || "".equals(authFileDir)) {
            authFileDir = AppAuthPathUtil.getAppJarPath() + "config/";
        }
        authFileDir = AppAuthPathUtil.dirPathFormate(authFileDir);
        Map<String, Object> map = this.verfiyAuthFile(authFileDir);
        if (Boolean.valueOf(map.get("isValid").toString())) {
            String authCode = map.get("authCode").toString();
            Long curentDateTime =Long.parseLong(map.get("curentDateTime").toString());
            AppAuthInterceptor.AUTH_FILE_CONTENT = authCode + ";" + curentDateTime;
            return true;
        }
        boolean bookeanAjax = (ajaxHeader != null && "XMLHttpRequest".toLowerCase().equals(ajaxHeader.toLowerCase())) || (contentType != null && contentType.toLowerCase().contains("application/json"));
        if (bookeanAjax) {
            ObjectMapper mapper = new ObjectMapper();
            JsonResult jsonResult = JsonResultUtil.failure(ErrorCode.SECURITY_NO_PASS.key, ErrorCode.SECURITY_NO_PASS.value, (Object) authUrl);
            String text = mapper.writeValueAsString((Object) jsonResult);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(text);
            return false;
        }
        AppAuthPostRedirectUtil postRedirect = AppAuthPostRedirectUtil.builderPostRedirect(response);
        String redirectUrl = "/rtAuth/index";
        postRedirect.sendByPost(redirectUrl);
        return false;

         */
    }

    public Map<String, Object> verifyAuthFile(String authFilePath) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isBlank(authFilePath)) {
            AppAuthInterceptor.log.error("没有配置授权文件路径，请检查配置文件配置！");
            map.put("isValid", false);
            return map;
        }
        authFilePath = AppAuthPathUtil.dirPathFormate(authFilePath);
        File file = new File(authFilePath + "auth.txt");
        if (!file.exists()) {
            AppAuthInterceptor.log.error("授权文件不存在，授权文件目录：{}", (Object) authFilePath);
            map.put("isValid", false);
            return map;
        }
        String text = AppAuthFileUtil.readTxtFile(file);
        String authCode = null;
        try {
            authCode = DefaultSecurityCoderUtil.decryptAES(text);
        } catch (Exception e2) {
            AppAuthInterceptor.log.error("授权文件被篡改！");
            map.put("isValid", false);
            return map;
        }
        String[] codes = authCode.split(";");
        if (codes.length != 3) {
            AppAuthInterceptor.log.error("授权文件被篡改,格式不正确！");
            map.put("isValid", false);
            return map;
        }
        String machineCode = codes[0];
        String endTime = codes[2];
        if (AppAuthInterceptor.MACHINE_CODE == null || AppAuthInterceptor.MACHINE_CODE.equals("")) {
            AppAuthInterceptor.MACHINE_CODE = AppAuthSerialNumberUtil.getMachineCodeSimple();
        }
        if (!AppAuthInterceptor.MACHINE_CODE.equals(machineCode)) {
            AppAuthInterceptor.log.error("授权机器码不匹配！,设备实时机器码：{},授权文件中的机器码：{},授权文件路径：{}", new Object[]{AppAuthInterceptor.MACHINE_CODE, machineCode, authFilePath + "auth.txt"});
            map.put("isValid", false);
            return map;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Long endDateTime = 0L;
        try {
            endDateTime = sdf.parse(endTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Long curentDateTime = System.currentTimeMillis();
        if (endDateTime <= curentDateTime) {
            AppAuthInterceptor.log.error("授权码已过期,授权过期时间：{}，当前时间：{},授权文件路径：{}", new Object[]{endDateTime, curentDateTime, machineCode, authFilePath + "auth.txt"});
            map.put("isValid", false);
            return map;
        }
        map.put("isValid", true);
        map.put("authCode", authCode);
        map.put("curentDateTime", curentDateTime);
        return map;
    }
    public static void setMachineCode(String machineCode) {
        AppAuthInterceptor.MACHINE_CODE = machineCode;
    }
    static {
        log = LoggerFactory.getLogger(AppAuthInterceptor.class);
    }
}
